from flask import Flask, render_template, request
import os
from werkzeug.utils import secure_filename

app = Flask(__name__)
app.config["UPLOAD_FOLDER"] = "uploads/"  # 设置上传文件夹路径
app.config["ALLOWED_EXTENSIONS"] = {"png", "jpg", "jpeg", "gif"}  # 允许的文件扩展名

# 确保上传文件夹存在
if not os.path.exists(app.config["UPLOAD_FOLDER"]):
    os.makedirs(app.config["UPLOAD_FOLDER"])


def allowed_file(filename):
    return (
        "." in filename
        and filename.rsplit(".", 1)[1].lower() in app.config["ALLOWED_EXTENSIONS"]
    )


@app.route("/", methods=["GET", "POST"])
def upload_file():
    if request.method == "POST":
        # 检查是否有文件在请求中
        files = request.files.getlist("file")
        if not files:
            return "没有文件部分"

        for file in files:
            if file:
                filename = secure_filename(file.filename)
                file.save(os.path.join(app.config["UPLOAD_FOLDER"], filename))
            else:
                return "文件类型不允许或文件未选择"

        return "所有文件已上传并保存"
    return render_template("upload.html")


if __name__ == "__main__":
    app.run(debug=True, port="5555", host="0.0.0.0")
